import dayjs from "dayjs";
import { usePublicHooks } from "../hooks";
import { reactive, ref, onMounted, h } from "vue";
import { message } from "@/utils/message";
import { addDialog } from '@/components/ReDialog'
import { ElMessageBox } from 'element-plus'
import { type FormItemProps } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import { useMapStoreHook } from "@/store/modules/map";
import elForm from '../form.vue'

import { taskareaList, taskareaAdd, taskareaUpdate, taskareaDel, updateStatus } from '@/utils/api/dispatch/jobRegion'
import { GetAllAgv } from '@/utils/api/dispatch/agv'

export function useDept() {
    const form = reactive({
        name: "",
        pageNumber: 0,
        pageSize: 100,
        sortName: "createtime",
        sortType: 0
    });

    const pureMap = useMapStoreHook()
    const formRef = ref();
    var dataList = ref([]);
    var agvCrossSwitch = ref(false)
    var expandOpen = ref(false)
    const dataListDeep = ref([])
    const loading = ref(true);
    const { tagStyle } = usePublicHooks();
    const pagination = reactive<PaginationProps>({
        total: 0,
        pageSize: 100,
        currentPage: 1,
        background: true
    });

    // 状态Select
    const SelectStatusOptions = reactive([
        { value: 1, label: '启用' },
        { value: 0, label: '禁用' },
        { value: 2, label: '锁定' },
    ])

    // 车辆Select
    const agvOptions = ref([])

    // 状态
    // function formatStatus(status) {
    //     const stateMap = {
    //         1: '启用',
    //         0: '禁用',
    //         2: '锁定'
    //     }
    //     return stateMap[status]
    // }
    function formatStatus(status) {
        if (status == 1) {
            return true
        } else {
            return false
        }
    }
    // 类型
    function formatType(status) {
        const stateMap = {
            // 0: '站点交管',
            1: '唯一区域交管',
            2: '巷道区域交管',
            3: '公共区域交管',
        }
        return stateMap[status]
    }

    const columns: TableColumnList = [
        {
            type: "expand",
            slot: "expand"
        },
        {
            label: "区域名称",
            prop: "name",
            width: 150,
            align: "left",
            sortable: true
        },
        {
            label: "状态",
            prop: "status",
            width: 80,
            cellRenderer: ({ row, props }) => (
                // <el-tag size={props.size} style={tagStyle.value(row.status)}>
                //   { formatStatus(row.status) }
                // </el-tag>

                <el-switch
                    modelValue={row.status}
                    // 如果状态是特定值需要转换，可以使用以下配置（示例用 1/0 表示状态）
                    active-value={1}
                    inactive-value={0}
                    size={props.size}
                    onChange={async (val) => {
                        // 这里可以添加状态更新后的逻辑
                        // row.status = val
                        // 如果需要可以在这里触发状态更新请求
                        // console.log(row);
                        const res = await updateStatus({ id: row.id, state: val })
                        if (res.Code === 0) {
                            row.status = val
                        }
                    }}
                    // inline-prompt
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                />
            )
        },
        {
            label: "操作",
            fixed: "right",
            slot: "operation"
        }
    ]

    async function onSearch() {
        loading.value = true;
        const { Content } = await taskareaList(form);
        // console.log('分页查询=>', Content);

        let newData = Content.Results;
        dataList.value = newData;
        dataListDeep.value = newData
        pagination.total = Content.TotalCount;
        pagination.pageSize = Content.PageSize;
        pagination.currentPage = Content.PageNumber + 1;

        setTimeout(() => {
            loading.value = false;
        }, 500);
    }

    // 交管列表切换
    function crossSearch() {
        if (agvCrossSwitch.value) {
            dataList.value = dataListDeep.value
            expandOpen.value = false
        } else {
            var agvCross = []
            const scoketCross = pureMap.scoketData.CrossMsgData.filter(v => {
                return v.AgvList.length !== 0
            })

            scoketCross.forEach(j => {
                const data = dataList.value.find(v => { return v.id === j.CrossId })
                agvCross.push(data)
            })
            dataList.value = agvCross
            expandOpen.value = true
        }
        agvCrossSwitch.value = !agvCrossSwitch.value
    }

    // 重置
    function resetForm(formEl) {
        if (!formEl) return;
        formEl.resetFields();
        onSearch();
    }

    // 删除
    function handleDelete(row) {
        ElMessageBox.confirm(
            `是否确认删除名称为${row.name}的数据项?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            taskareaDel(row.id).then(res => {
                if (res.Code === 0) {
                    message(`您删除了名称为${row.name}的这条数据`, { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    function handleSizeChange(val: number) {
        form.pageSize = val
        onSearch()
    }

    function handleCurrentChange(val: number) {
        form.pageNumber = val - 1
        onSearch()
    }

    onMounted(async () => {
        onSearch()

        // 站点下拉
        const { Content } = await GetAllAgv()
        agvOptions.value = Content
    })

    return {
        columns,
        loading,
        dataList,
        handleDelete,
        form,
        onSearch,
        resetForm,
        pagination,
        handleSizeChange,
        handleCurrentChange,
        crossSearch,
        expandOpen,
        agvCrossSwitch
    }
}